<?php
namespace Admin\Controller;
use Think\Controller;
class UserController extends CommonController {

	/**
	* [index 展示用户信息]
	*/
	public function index(){

		$user = M('user');
		//获取关键字
		if(!empty($_GET['search_username'])){
			//有关键字
			$where = "username like '%".$_GET['search_username']."%'";
		}else{
			$where = '';
		}

		// 定义每页显示条目
		$num = I('get.prepage')?I('get.prepage'):5;
		// 查询满足要求的总记录数
		$count = $user->where($where)->count();
		// 实例化分页类 传入总记录数和每页显示的记录数
		$Page = new \Think\Page($count,$num);

		//获取limit参数
		$limit = $Page->firstRow.','.$Page->listRows;
		// 查询zz_user表中基本字段信息, 分配给模板展示
		$res = $user->field('user_id, username, lasttime, lock, online')->where($where)->limit($limit)->select();

		// 分页显示输出
		$pages = $Page->show();
		$allpage = $Page->totalPages;
		$p = $_GET['p']?$_GET['p']:1;

		if ($p==$allpage) {
			$rows =  $count - ($allpage-1)*$num;
		}else{
			$rows = $num;
		}

		// 分配一些页码信息
		$this->assign('total',$count);
		$this->assign('test','用户列表');
		$this->assign('rows',$rows);
		$this->assign('allpage',$allpage);
		$this->assign('p',$p);
		$this->assign('pages',$pages);
		$this->assign('res', $res);
		$this->display();
	}


	/**
	 * [add 用户添加]
	 */
	public function add(){

		$this->display();
	}


	/**
	 * [insert 用户添加处理页面]
	 */
	public function insert(){
		if (IS_POST) {

			// 用户名邮箱正则验证
			$regex = '/^[\w\.]+@\w+(\.\w+)+(\.\w+)*/i';
			if(!preg_match($regex,$_POST['username'])){
				$this->error('请输入有效的邮箱');
				exit;
			}

			// 用密码正则验证
			$regex = '/^[\S]{6,18}$/';
			if(!preg_match($regex,$_POST['password'])){
				$this->error('请输入6-18位长度的密码');
				exit;
			}

			// 用昵称不能为空验证
			if($_POST['nickname']==''){
				$this->error('昵称不能为空');
				exit;
			}
			// 处理表单数据
			$birthday = I('post.birthday');
			$_POST['birthday'] = transfBirth($birthday);
			$_POST['password'] = md5(I('post.password'));
			$_POST['regtime'] = $_SERVER['REQUEST_TIME'];
			$_POST['regip'] = $_SERVER['REMOTE_ADDR'];// 添加是ip地址
			// $_POST['tag_id'] = implode(',', I('post.tag_id'));
			$_POST['email_token'] = md5(I('post.username').I('post.password'));// 加密email验证码,为用户名和密码
			$_POST['email_state'] = 1;
			// 调用图片上传函数, 处理图片
			$str = Uploads('photo');
			if ($str) {
				$_POST['photo'] = $str;
			}

			$m = M();
			// 开启事务
			$m->startTrans();

			$user = M('user');
			$user->create();

			$id = $user->add();
			if (!$id) {
				$m->rollback();
				$this->error('添加失败');
			}

			$_POST['user_id'] = $id;
			$userinfo = M('user_info');
			$userinfo->create();
			$res = $userinfo->add();

			// 添加成功提交事务,  添加失败回滚事务
			if ($res) {
				//初始化新用户数据表
				$albumsData1 = array(
				    'albums_name' => '贴图相册',
				    'albums_type' => 0,
				    'user_id'     => $result['user_id'],
				    'time'        => $_SERVER['REQUEST_TIME'],
				);
				$albumsData2 = array(
				    'albums_name' => '共享相册',
				    'albums_type' => 1,
				    'user_id'     => $result['user_id'],
				    'time'        => $_SERVER['REQUEST_TIME'],
				);
				$albums = M('albums');
				$albums->add($albumsData1);
				$albums->add($albumsData2);
				$m->commit();
				$this->success('添加成功', U('index'));
			} else {
				$m->rollback();
				$this->error('添加失败');
			}

		}else{
			E('你访问的页面不存在');
		}
	}


	/**
	 * [edit 用户编辑页面]
	 */
	public function edit(){

		// 获得用户id
		$id = $_GET['id'];
		$user = M('user');
		$res = $user->alias('u')->join('zz_user_info ui on u.user_id=ui.user_id')->where("u.user_id='$id'")->select();


		//时间戳转为m-d-y格式的字符串
		$res[0]['birthday'] = transfBirth($res[0]['birthday'], false);
		$this->assign('res', $res);

		$this->display();
	}


	/**
	 * [editdo 用户编辑处理页面]
	 */
	public function editdo(){

		// 用户名邮箱正则验证
		$regex = '/^[\w\.]+@\w+(\.\w+)+(\.\w+)*/i';
		if(!preg_match($regex,$_POST['username'])){
			$this->error('请输入有效的邮箱');
			exit;
		}

		// 用昵称不能为空验证
		if($_POST['nickname']==''){
			$this->error('昵称不能为空');
			exit;
		}

		// 如果选择重置密码, 密码重置为用户名
		if (I('post.repass')) {
			$_POST['password'] = md5(I('post.username'));
		}

		// 如果上传头像, 进行图片上传处理
		if ($_FILES['photo']['error'] == 0) {
			$str = Uploads('photo');
			if ($str) {
				$_POST['photo'] = $str;
			}
		}

		// 处理表单数据
		$birthday = I('post.birthday');
		$_POST['birthday'] = transfBirth($birthday);

		$m = M();
		// 开启事务
		$m->startTrans();

		$user = M('user');
		$user->create();

		$id = $user->save();

		$userinfo = M('user_info');
		$userinfo->create();
		$res = $userinfo->save();

		// $this->redirect();
		// 添加成功提交事务,  添加失败回滚事务
		if (!$res && !$id) {
			$m->rollback();

			$this->error('修改失败');
		} else {
			$this->success('修改成功', U('index'));
			$m->commit();
		}
	}


	/**
	* [delete 删除用户]
	*  前台发ajax请求, 提交到该控制器
	*/
	public function delete(){

			$m = M();
			$id = I('get.user_id');
			// 开启事务
			$m->startTrans();

			$user = M('user');
			$userinfo = M('user_info');
			$deluser = $user->delete($id);
			$deluserinfo = $userinfo->delete($id);

			// 删除成功提交事务, 并返回ajax值1, 删除失败回滚事务, 返回ajax值0
			//
			// $deluser = 0;

			if ($deluser && $deluserinfo) {
				$m->commit();
				$this->redirect('index');
			} else {
				$m->rollback();
				$this->error('删除失败');
			}

	}


	/**
	* [detail ajax请求, 返回详细信息]
	* @return [type] [description]
	*/
	public function detail(){
		if (IS_AJAX) {
			$id = I('post.id');
			$user = M('user');
			$res = $user->alias('u')->join('zz_user_info ui on u.user_id=ui.user_id')->where("u.user_id='$id'")->select();

			if ($res) {
				// 查询标签
				if ($res[0]['sex']==0) {
					$res[0]['sex'] = '女';
				} elseif ($res[0]['sex']==1) {
					$res[0]['sex'] = '男';
				} else{
					$res[0]['sex'] = '保密';
				}


				$res[0]['birthday'] = date('Y-m-d', $res[0]['birthday']);
				$res[0]['regtime'] = date('Y-m-d h:i:s', $res[0]['regtime']);
				$res[0]['tag'] = $res[0]['tag']?$res[0]['tag']:'/';
				$res[0]['area'] = $res[0]['area']?$res[0]['area']:'/';

				$res[0]['lastip'] = $res[0]['lastip']?$res[0]['lastip']:'/';
				$res[0]['regip'] = $res[0]['regip']?$res[0]['regip']:'/';
				$res[0]['signature'] = $res[0]['signature']?$res[0]['signature']:'/';
				$app=__ROOT__;
// 拼接字符串
$html = <<<HELLO
				  <div class="col-lg-12">
					<section class="panel">
						<div class="panel-body">
							<a href="#" class="task-thumb">
								<img src="{$app}/Public{$res[0]['photo']}" width="90px" height="90px"></a>
							<div class="task-thumb-details">
								<h1>
									<a href="#">{$res[0]['nickname']}</a>
								</h1>
								<p>{$res[0]['sex']}</p>
							</div>
						</div>
						<table class="table table-hover ">
							<tbody>
								<tr>
									<td><i class=" icon-tasks"></i></td>
									<td>注册时间</td>
									<td >{$res[0]['regtime']}</td>
								</tr>
								<tr>
									<td ><i class="icon-calendar"></i></td>
									<td>生日</td>
									<td>{$res[0]['birthday']}</td>
								</tr>
								<tr>
									<td><i class="icon-map-marker"></i></td>
									<td>地区</td>
									<td>{$res[0]['area']}</td>
								</tr>
								<tr>
									<td><i class="icon-leaf"></i></td>
									<td>标签</td>
									<td>{$res[0]['tag']}</td>
								</tr>
								<tr>
									<td><i class="icon-qrcode"></i></td>
									<td>上次IP</td>
									<td>{$res[0]['lastip']}</td>
								</tr>
								<tr>
									<td><i class="icon-code-fork"></i></td>
									<td>注册IP</td>
									<td>{$res[0]['regip']}</td>
								</tr>
								<tr>
									<td >
										<i class=" icon-bell-alt"></i>
									</td>
									<td  style="width:90px;padding-left:1px;padding-right:1px;">签名</td>
									<td ><p style="width:375px;word-wrap:break-word">{$res[0]['signature']}</p></td>
								</tr>
							</tbody>
						</table>
					</section>
				</div>
HELLO;

				$this->ajaxReturn($html);
			} else {
				$this->ajaxReturn(false);
			}

		}else{
			E('你访问的页面不存在');
		}
	}

}
